package com.newtouch.xcd.cms.job.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Reference;
import com.newtouch.xcd.cms.config.FeignCrmConfig;
import com.newtouch.xcd.cms.service.impl.FeignCrmService;
import com.newtouch.xcd.cms.to.crm.CrmFinancialProductData;
import com.newtouch.xcd.common.constants.BaseDict;
import com.newtouch.xcd.common.constants.ResponseCode;
import com.newtouch.xcd.common.to.CommonResult;
import com.newtouch.xcd.mft.vo.CrmBookFundProductReq;
import com.newtouch.xcd.pms.entity.XcdFundOrder;
import com.newtouch.xcd.pms.service.XcdFundOrderService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class BookFundProductJobHandler extends IJobHandler {

    @Reference
    XcdFundOrderService fundOrderService;

    @Autowired
    FeignCrmService feignCrmService;

    @Autowired
    private FeignCrmConfig feignCrmConfig;

    @XxlJob(value = "BookFundProductJobHandler")
    @Override
    public ReturnT<String> execute(String s) throws Exception {

        Map<String, Boolean> successMap = new ConcurrentHashMap<>();
        Boolean successFlag = true;
        List<Thread> threads = new ArrayList<>();

        String token = this.feignCrmConfig.getToken();

        List<XcdFundOrder> orders = this.fundOrderService.queryByBookStatus(BaseDict.BookStatus.B00.getCode());

        if (CollUtil.isEmpty(orders)) {
            XxlJobLogger.log("待更新产品预约条数为0");
            return ReturnT.SUCCESS;
        }

        for (XcdFundOrder order : orders) {
            Thread thread = new Thread(() -> {

                CrmBookFundProductReq req = new CrmBookFundProductReq();
                req.setRequestId(order.getRequestId());
                req.setProductId(order.getProductId());
                req.setCustomerName(order.getCustomerName());
                req.setCustomerPhone(order.getCustomerPhone());
                req.setBookingAmount(order.getBookingAmount());
                req.setReference(order.getReference());
                req.setBookSubmitTime(order.getBookSubmitTime());

                CommonResult<CrmFinancialProductData> response = null;
                try {
                    response = this.feignCrmService.bookFundProduct(req, token, "Fund", "fundProductBook");

                    if (ResponseCode.R200.getCode().equals(response.getCode()) || ResponseCode.R502.getCode().equals(response.getCode())) {
                        order.setBookStatus(BaseDict.BookStatus.B01.getCode());
                        this.fundOrderService.saveOrUpdate(order);
                        XxlJobLogger.log("requestId:{},提交预约成功。", order.getRequestId());
                    } else {
                        successMap.put(order.getRequestId(), false);
                        XxlJobLogger.log("requestId:{},提交预约失败。失败原因:{}", order.getRequestId(), response.getMessage());
                    }

                } catch (Exception e) {
                    successMap.put(order.getRequestId(), false);
                    XxlJobLogger.log("requestId:{},提交预约失败。失败原因:{}", order.getRequestId(), response.getMessage());
                }
            });
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        for (String requestId : successMap.keySet()) {
            if (successMap.get(requestId) == false) {
                successFlag = false;
            }
        }

        if (successFlag) {
            return ReturnT.SUCCESS;
        } else {
            return ReturnT.FAIL;
        }
    }
}
